package atom.core3.security.help;

import java.io.FileOutputStream;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SecureRandom;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;

import es.sing.util.GeneraClaves;

public class MakeRawKey
{
	private PrivateKey priKey;

	private PublicKey pubKey;

	private KeyPair keyPair;

	//algorithm="RSA" keysize=1024 
	public void generateKeyPair(String algorithm,int keysize) throws Exception
	{
		KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(algorithm);
		keyPairGen.initialize(keysize, new SecureRandom());

		keyPair = keyPairGen.generateKeyPair();
		priKey = (RSAPrivateKey) keyPair.getPrivate();
		pubKey = (RSAPublicKey) keyPair.getPublic();

	}
	//algorithm="RSA" keysize=1024 
	public void generateKeyPair2(String algorithm,int keysize)
	{
		// 用RSA算法产生用户密钥对
		keyPair = GeneraClaves.generaParClaves(keysize,	algorithm);
		priKey = (RSAPrivateKey) keyPair.getPrivate();
		pubKey = (RSAPublicKey) keyPair.getPublic();
		
	}
	public void saveKeyPair(String publicKeyFile, String privateKeyFile) throws Exception
	{
		// save public key
		byte[] key1 = pubKey.getEncoded();
		byte[] key2 = priKey.getEncoded();
		// 构造公钥文件并写入公钥
		FileOutputStream keyFile1 = new FileOutputStream(publicKeyFile);
		keyFile1.write(key1);
		keyFile1.close();
		// 构造私钥文件并写入私钥
		keyFile1 = new FileOutputStream(privateKeyFile);
		keyFile1.write(key2);
		keyFile1.close();
	}

}
